@echo off & setlocal enabledelayedexpansion

REM CAUTION! THIS FILE CANNOT SUPPORT UNICODE CHARACTERS!
REM DO NOT USE UNICODE CHARACTERS IN PATH, VARIABLE, AND COMMENT, ETC.
REM
REM # Build Script for FastDDS Python Library on Windows platform
REM
REM Module: MIAHX(C) / FFST / IFIRM
REM
REM
REM Version: 0.4.5,
REM Last updated: May 22, 2024
REM
REM Combining all user-defined message structs into src/MiahxProto.idl,
REM and generating C++ and Python sources that FastDDS requires
REM
REM ## Contributor(s)
REM * YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>
REM
REM ## Change log
REM ### v0.4.5
REM - .22 [Update] Adds `-de final` into the FastDDSGen calling,
REM                specifying FINAL as the default extensibility of IDL types, so as to support Zero-Copy
REM ### v0.4.5
REM - .10 [New] Adds features
REM
REM Copyright (C) 2024-2025 MIAHX Contributors, ISCAS, and ASIC. All Rights Reserved.
REM Licensed under Apache-2.0.


echo -- Building `miahx_fastdds_api`

REM Activate Visual C++ 2019 Vars
set VcVars64_Path=
set toolpath="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
set version=[16,17)
for /f "delims=" %%I in ('%toolpath% -latest -version !version! -products * -requires Microsoft.VisualStudio.Workload.NativeDesktop -property installationPath') do (
  set VsInstallDir=%%I\
)
set VcVars64_Path=%VsInstallDir%VC\Auxiliary\Build\vcvars64.bat
if not exist "%VcVars64_Path%%" (
  echo ERROR: `vcvars64.bat` not found (Microsoft Visual Studio 2019 is recommended)
) else (
  echo -- Found `vcvars64.bat`: "%VcVars64_Path%"
  call "%VcVars64_Path%"
)

set CC_FASTDDS_IDL_PKG_HOME=src\miahx_fastdds_types
set CC_FASTDDS_IDL_PKG_NAME=MiahxFastDDSTypes

set LIB_MIAHX_FASTDDS=miahx_fastdds
set LIB_MIAHX_FASTDDS_API=miahx_fastdds_api

REM Combine all user-defined FastDDS IDL files into one
set TARGET_FASTDDS_IDL=%~dp0%CC_FASTDDS_IDL_PKG_HOME%\%CC_FASTDDS_IDL_PKG_NAME%.idl
copy /y /b %~dp0..\idl\*.idl %TARGET_FASTDDS_IDL%
echo -- Merging FastDDS IDL files - done

REM Generate CMake and C++ source files
REM Use FastDDSGen v3.3.0
REM -de,-default_extensibility <ext>: sets the default extensibility for types without the @extensibility annotation.
cd %CC_FASTDDS_IDL_PKG_HOME%
call fastddsgen -replace -python %CC_FASTDDS_IDL_PKG_NAME%.idl -de final
echo -- Generating C++ source files - done

REM Build with colcon
pip install -U -i https://pypi.tuna.tsinghua.edu.cn/simple colcon-common-extensions vcstool wheel loguru
colcon build
cd %~dp0
mkdir src\%LIB_MIAHX_FASTDDS%
copy /y %CC_FASTDDS_IDL_PKG_HOME%\install\%CC_FASTDDS_IDL_PKG_NAME%\lib\site-packages\%CC_FASTDDS_IDL_PKG_NAME%.py src\%LIB_MIAHX_FASTDDS%\__init__.py
copy /y %CC_FASTDDS_IDL_PKG_HOME%\install\%CC_FASTDDS_IDL_PKG_NAME%\lib\site-packages\_%CC_FASTDDS_IDL_PKG_NAME%Wrapper.pyd src\%LIB_MIAHX_FASTDDS%
copy /y %CC_FASTDDS_IDL_PKG_HOME%\install\%CC_FASTDDS_IDL_PKG_NAME%\bin\%CC_FASTDDS_IDL_PKG_NAME%.dll src\%LIB_MIAHX_FASTDDS%
echo -- Building `miahx_fastdds_api` - done